package ru.nsu.fit.ws.send_answer;

import ru.nsu.fit.shared.data_base_manager.DatabaseManager;
import ru.nsu.fit.shared.error_codes.ErrorCodes;

import javax.jws.HandlerChain;
import javax.jws.WebService;
import java.sql.SQLException;

import static ru.nsu.fit.shared.error_codes.ErrorCodes.*;

/**
 * Created by IntelliJ IDEA.
 * User: vtimofeev
 * Date: 12/6/12
 * Time: 9:15 AM
 * To change this template use File | Settings | File Templates.
 */

@WebService(endpointInterface = "ru.nsu.fit.ws.send_answer.AnswerSender")
@HandlerChain(file= "handler-chain.xml")
public class AnswerSenderImpl implements AnswerSender{
    @Override
    public AnswerOutput sendAnswer(AnswerInput input) {

        long userSessionId = input.getUserSessionId();
        int questionID = input.getQuestionId();
        int answerId = input.getAnswerId();

        try {

            int userID = DatabaseManager.getUserId(userSessionId);
            if (userID < 0) {
                return createAnswerOutput(false, NOT_AUTHORIZED);
            }

            boolean answerIDExistent = DatabaseManager.checkAnswerID(questionID, answerId);
            if (!answerIDExistent) {
                return createAnswerOutput(false, ILLEGAL_QUESTION_OPTION);
            }
            boolean answeredBefore = DatabaseManager.hasAnsweredBefore(userID, questionID);
            if (answeredBefore) {
                return createAnswerOutput(false, QUESTION_WAS_ANSWERED);
            }

            DatabaseManager.addAnswer(userID, answerId);
            return createAnswerOutput(true, NO_ERROR);

        } catch (SQLException e) {
            e.printStackTrace();
            return createAnswerOutput(false, DATABASE_ERROR);
        }
    }

    private AnswerOutput createAnswerOutput(boolean successful, ErrorCodes errorCode) {

        AnswerOutput output = new AnswerOutput();

        output.setSuccessful(successful);
        output.setErrorCode(errorCode.getCode());
        output.setErrorMessage(errorCode.getMessage());

        return output;
    }
}
